package com.pat.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.pat.manager.MobilePhoneManager;
import com.pat.om.Envelope;
import com.pat.om.Mezzage;
import com.pat.om.MobilePhone;

public final class GCMUtil {

	private static final String GCM_SERVER_API_KEY = "AIzaSyDWPY0jyh6N8aiziu7N6eOkhA_RCtIOfYQ";

	/**
	 * Post message to GCM
	 * 
	 * @param str
	 * @param jsonObject
	 */
	public static void post(JSONObject jsonObject) {
		URL url;
		try {
			url = new URL("https://android.googleapis.com/gcm/send");

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Authorization", "key="
					+ "AIzaSyAxQibSilNJNmYphYqizglFNt7AoiBFTPg");

			OutputStream os = conn.getOutputStream();

			os.write(jsonObject.toString().getBytes());

			os.flush();

			if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			String output;
			System.out.println("Output from Server .... \n");
			while ((output = br.readLine()) != null) {
				System.out.println(output);
			}

			conn.disconnect();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Result send2(Envelope envelope) {

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("registration_ids", envelope.getReceiverRegId());
			jsonObject.put("data", envelope.getData());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		post(jsonObject);
		return null;
	}

	public static Result send(Envelope envelope) {
		Sender sender = new Sender(GCM_SERVER_API_KEY);
		Message message = new Message.Builder().addData("data",
				envelope.getData()).build();
		Result result = null;
		try {
			result = sender.send(message, envelope.getReceiverRegId(), 5);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static Result send(Mezzage mezzage) {
		Sender sender = new Sender(GCM_SERVER_API_KEY);
		Message message = new Message.Builder().addData("data",
				mezzage.getData()).build();
		Result result = null;
		try {
			String recieverId = getGCMId(mezzage.getReceiverNumber());
			result = sender.send(message, recieverId, 5);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;

	}

	private static String getGCMId(String receiverNumber) {
		MobilePhoneManager mobilePhoneManager = new MobilePhoneManager();
		List<MobilePhone> list = mobilePhoneManager.get(receiverNumber);
		
		return list.get(0).getGcmRegistration();
	}
}